import numpy as np
import pandas as pd

def actionDetail(x):
    
    recent_action=0#最近安装的APP数量
    recent_cat=0#最近安装同类APP数量
    
    c_time=int(str(x.clickTime))      
    
    if not isinstance(x.actionList,float):
        time_list=[int(i) for i in x.timeList.strip().split(' ')]
        action_list=x.actionList.strip().split(' ')
        type_list=x.action_type.strip().split(' ')
        
        for i in range(len(action_list)):
            if time_list[i]<c_time:
                
                recent_action+=1

                atype=int(type_list[i])
                
                if atype<100:
                    main=atype
                    sub=0
                else:
                    main=atype//100
                    sub=atype%100
                
                if x.appTypeFirst==main and x.appTypeSecond==sub:
                    recent_cat+=1
            else:
                #因为是按照升续排列，所以这里要可以跳出了
                break
    
    re=str(recent_action)+','+str(recent_cat)
    
    return re
    
def getrecent_action(x):
    return x.App_Detail.split(',')[0]

def getrecent_cat(x):
    return x.App_Detail.split(',')[1]

def digActionDetail(data_type='train'):
    df_output=''
    save_path=''
    if data_type=='train':
        df_output=pd.read_csv('data/cutData/feature_v2.csv')
        save_path='data/cutData/feature_v3.csv'
    elif data_type=='test':
        df_output=pd.read_csv('data/cutData/test_v2.csv')
        save_path='data/cutData/test_v3.csv'
    else:
        print('data_type出错！')
        return
    
    df_detail=pd.read_csv('data/feature/action_list_v1.csv')
    
    df_output=pd.merge(df_output,df_detail,how='left',on='userID')
    
    print('开始统计')
    
    del df_detail
        
    df_output['App_Detail']=df_output.apply(lambda x:actionDetail(x),axis=1)
    
    print('APP统计完成')
    
    df_output['recent_action']=df_output.apply(lambda x:getrecent_action(x),axis=1)
    df_output['recent_cat']=df_output.apply(lambda x:getrecent_cat(x),axis=1)

    #去除无用信息
    df_output=df_output.drop(['App_Detail','actionList','action_type','timeList'],axis=1)
    
    print('开始保存')
    df_output.to_csv(save_path,index=False) 

    
if __name__=='__main__':
    digActionDetail(data_type='train')
    digActionDetail(data_type='test')
